package com.alan.service.impl;

import com.alan.domain.entity.LoginUser;
import com.alan.domain.entity.User;
import com.alan.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    /**
     * @param userName: 前台传过来的用户名，利用该信息查询数据库
     * @return
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //根据用户名查询信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userName);
        User user = userMapper.selectOne(queryWrapper);
        //如果没查到，抛出异常
        if (Objects.isNull(user)){
            //TODO: 异常统一处理
            throw new RuntimeException("User not found");
        }
        //查询成功，返回用户信息
        //TODO: 查询封装权限信息
        return new LoginUser(user);
    }
}
